package com.authine.cloudpivot.web.sso.template;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.authine.cloudpivot.engine.api.model.organization.UserModel;
import com.authine.cloudpivot.web.api.util.HttpUtilNew;
import com.authine.cloudpivot.web.sso.exception.UserException;
import com.authine.cloudpivot.web.sso.exception.UserNotExistException;
import com.authine.cloudpivot.web.sso.security.BaseAuthenticationToken;
import com.authine.cloudpivot.web.sso.view.ThreadLocalValue;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpMethod;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
public class WeChatTicketLogin extends BaseSimpleTemplate {
    WeChatTicketLogin() {
        super(SimpleTemplateConfig.builder().requestMatcher(new AntPathRequestMatcher("/login/wx/ajax", HttpMethod.GET.name()))
                .redirectClientID("api").responseType(ResponseTypeEnum.JSON)
                .build());
    }

    @Override
    public String getSourceId(BaseAuthenticationToken token) throws Exception {
        long start = System.currentTimeMillis();
        String accessToken = getDubboConfigService().getOrganizationFacade().getAccessToken(token.getCorpId(),"WECHAT" );
        //String accessToken = "zesyrkYwsPRah2oRKWOixsfZHTJNFQSLu6trFREMXGizBnFU6YCuLylk2lMTYlfYymJ3wBeadCEata_5QVYV32cJv1Nz8K6t7sPIOS0xufcLC1D9Ap5XgUA_XDbX7TA0ENR0jeHYJ-CMriXHAwC5GIaF-hksiExN-iqHXS2Z7gIXSrKxVmaRvYkglV-rjlWjEsQQrQLDRX6ckx_7xZPacg";
        log.debug("微信应用内登录引擎获取accesstoken时间：{}",System.currentTimeMillis()-start);
        long start2 = System.currentTimeMillis();
        Map<String,Object> param = new HashMap<>(4);
        param.put("access_token",accessToken);
        param.put("code",token.getCode());
        String response = HttpUtil.get("https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo", param);
        log.debug("微信应用内登录，调用微信getuserinfo接口时间：{}",System.currentTimeMillis()-start2);
        log.info("返回结果： " + response);
        JSONObject jsonObject = JSONObject.parseObject(response);
        String errcode = jsonObject.getString("errcode");
        if (StringUtils.isNotBlank(errcode)) {
            switch(errcode) {
                case "50001":
                    log.warn("获取用户关联信息失败，失败响应："+response);
                    throw new UserException("redirect_url未在微信登记可信域名，请检查微信授权回调域设置是否正确");
                default:
                    break;
            }
        }
        String sourceId = jsonObject.get("UserId")==null?null:String.valueOf(jsonObject.get("UserId"));
        if(StringUtils.isBlank(sourceId)){
            String openid = jsonObject.get("OpenId")==null?null:String.valueOf(jsonObject.get("OpenId"));
            //进行openid转userid
            Map<String, Object> param2 = new HashMap<>();
            param2.put("openid",openid);
            String response2 = HttpUtilNew.sendHttpPost("https://qyapi.weixin.qq.com/cgi-bin/user/convert_to_userid?debug=1&access_token=" + accessToken, JSONObject.toJSONString(param2));
            log.info("返回结果： " + response2);
            JSONObject jsonObject2 = JSONObject.parseObject(response2);
            sourceId = jsonObject2.get("userid")==null?null:String.valueOf(jsonObject2.get("userid"));
        }
        if (StringUtils.isBlank(sourceId)) {
            log.warn("获取用户关联信息失败，失败响应："+response);
            throw new UserNotExistException("获取微信用户失败");
        }
        log.debug("从企业微信获取的userId为：" + sourceId);
        return sourceId;


    }


    @Override
    public UserModel getUser(Object sourceId) {
        return dubboConfigService.getOrganizationFacade().getUserByUserIdAndCorpId(String.valueOf(sourceId), ThreadLocalValue.localCorpId.get());
    }
}
